package com.dlc.shop.seckill.common.listener;

import com.dlc.shop.bean.enums.OrderType;
import com.dlc.shop.bean.event.PaySuccessOrderEvent;
import com.dlc.shop.bean.model.OrderItem;
import com.dlc.shop.bean.order.PaySuccessOrderOrder;
import com.dlc.shop.manager.impl.StockManager;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 秒杀成功回调
 * @author LGH
 */
@Component("seckillPaySuccessListener")
@AllArgsConstructor
public class PaySuccessOrderListener {

    private StockManager stockManager;

    /**
     * 更新秒杀状态
     */
    @EventListener(PaySuccessOrderEvent.class)
    @Order(PaySuccessOrderOrder.SECKILL)
    public void seckillPaySuccessListener(PaySuccessOrderEvent event) {
        List<com.dlc.shop.bean.model.Order> orders = event.getOrders();

        for (com.dlc.shop.bean.model.Order order : orders) {
            if (!Objects.equals(order.getOrderType(), OrderType.SECKILL.value())) {
                return;
            }
            OrderItem orderItem = order.getOrderItems().get(0);
            // 解锁秒杀库存锁定数量，增加销量
            stockManager.handlePaySuccessSecKillStock(orderItem.getProdCount(), order.getOrderNumber());
        }

    }
}
